package com.htdata.iiot.api.tsdb.pojo;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;

public class DataPointDeserializer extends JsonDeserializer<DataPoint> {

	@Override
	public DataPoint deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		DataPoint dataPoint = new DataPoint();
		JsonNode node = jp.getCodec().readTree(jp);
		String idStr = node.get("dn").asText();
		DeviceNumber dn = DeviceNumber.fromBase64String(idStr);
		dataPoint.setDeviceNumber(dn);
		long ts = node.get("ts").asLong();
		dataPoint.setTs(ts);
		String metricName = node.get("metric").asText();
		double value = node.get("value").asDouble();
		dataPoint.setMetric(new Metric(metricName, value));
		JsonNode tagsNode = node.get("tags");
		if (tagsNode != null) {
			Iterator<Entry<String, JsonNode>> iter = tagsNode.fields();
			while (iter.hasNext()) {
				Entry<String, JsonNode> field = iter.next();
				dataPoint.addTag(field.getKey(), field.getValue().asText());
			}
		}
		

		return dataPoint;
	}

}
